<template>
  <div>
    <div
      class="practice-test"
      :style="{
        background: '#f2f2f2',
        minHeight: '100vh',
        textAlign: 'left',
        opacity: !submit ? 1 : 0,
      }"
    >
      <div class="header">
        <div class="header-title van-ellipsis">{{ practiceTitle }}</div>
        <div class="header-page">
          <span class="nav" @click="changePage('prev')"><</span>
          <span style="color: #0043e7">
            {{ current_page + 1 }}
          </span>
          /{{ practiceList.length }}
          <span class="nav" @click="changePage('next')">></span>
        </div>
      </div>
      <div class="content">
        <van-swipe
          ref="swiper"
          style="
            min-height: calc(100vh - 80px);
            margin: 0 25px;
            box-sizing: border-box;
          "
          :show-indicators="false"
          @change="onChange"
        >
          <van-swipe-item v-if="practiceList.length === 0">
            <van-empty style="width: 100%" description="还什么都没有哦~" />
          </van-swipe-item>
          <van-swipe-item
            v-for="(practiceItem, index) in practiceList"
            :key="index"
          >
            <div class="title" v-html="practiceItem.title"></div>
            <div class="select-options">
              <van-checkbox-group :value="answer.answer">
                <van-checkbox
                  @click="checkChange(item.value)"
                  v-for="(item, index) in practiceItem.selectOptions"
                  :key="index"
                  :name="item.value"
                >
                  <div
                    :class="{
                      green:
                        (!answer.status &&
                          answer.answer.indexOf(item.value) !== -1) ||
                        (answer.status &&
                          practiceItem.correctValue.indexOf(item.value) !== -1),
                      error:
                        answer.status &&
                        answer.answer.indexOf(item.value) !== -1 &&
                        practiceItem.correctValue.indexOf(item.value) === -1,
                    }"
                  >
                    {{ item.text }}
                  </div>
                  <template #icon="props">
                    <div
                      :class="{
                        img_icon: true,
                        green_border:
                          (!answer.status &&
                            answer.answer.indexOf(item.value) !== -1) ||
                          (answer.status &&
                            practiceItem.correctValue.indexOf(item.value) !==
                              -1),
                      }"
                      :style="{
                        borderColor:
                          (!answer.status &&
                            answer.answer.indexOf(item.value) !== -1) ||
                          (answer.status &&
                            practiceItem.correctValue.indexOf(item.value) !==
                              -1)
                            ? '#54d100'
                            : '#000',
                      }"
                    >
                      <div
                        :style="`background-color:${
                          (!answer.status &&
                            answer.answer.indexOf(item.value) !== -1) ||
                          (answer.status &&
                            practiceItem.correctValue.indexOf(item.value) !==
                              -1)
                            ? '#54d100'
                            : '#000'
                        }`"
                        v-show="
                          props.checked ||
                          (answer.status &&
                            practiceItem.correctValue.indexOf(item.value) !==
                              -1)
                        "
                      ></div>
                    </div>
                  </template>
                </van-checkbox>
              </van-checkbox-group>
              <div
                v-if="practiceList[current_page].type === 2"
                class="submit-button"
                @click="confirm"
              ></div>
            </div>
            <div v-show="answer.status" class="answer green">
              参考答案：{{ valueText }}
            </div>
            <div
              v-show="answer.status"
              class="answer-desc"
              v-html="
                practiceItem && practiceItem.analysis
                  ? '参考解析' + practiceItem.analysis
                  : '参考解析: 暂无'
              "
            >
              参考解析：小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼
              小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼
            </div>
          </van-swipe-item>
        </van-swipe>
      </div>
      <div class="operation" style="bottom: 0">
        <!-- <div v-if="$route.query.type == 1" @click="collect">收藏</div> -->
        <div v-if="$route.query.type == 1" @click="removeError">移除错题</div>
        <div v-if="$route.query.type == 2" @click="removeCollect">移除收藏</div>
        <div @click="$router.go(-1)">返回上一页</div>
      </div>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
export default {
  data() {
    this.setTimeoutId = null;
    return {
      practiceTitle: "", // 页面的标题
      current_page: 0, // 当前页数
      total_page: 0, // 总页数
      practiceList: [], // 练习习题列表
      answerList: [], // 用户的答案记录列表
      answer: { status: false, answer: [] }, // 用户当前题的做题的答案
      answerMake: [], // 记录正误的数组
      lookAnswerStatus: false, // 查看答题卡
      submit: false, // 交卷
    };
  },
  mounted() {
    this.loadData();
  },
  watch: {
    answerList: {
      deep: true,
      handler(val) {
        // console.log(val, "val");
        // 计算错了多少道题目
        val.map((item, index) => {
          if (item.answer.length <= 0) return;
          let current = [...item.answer].sort().join(",");
          let correct = (this.practiceList[index]
            ? [...this.practiceList[index].correctValue]
            : []
          )
            .sort()
            .join(",");
          // // console.log(current == correct, index);
          if (current === correct) {
            this.answerMake[index] = true;
          } else {
            this.answerMake[index] = false;
          }
        });
      },
    },
  },
  computed: {
    valueText() {
      // console.log(this.practiceList[this.current_page]);
      return this.practiceList[this.current_page].correctValue
        .map((item) => {
          if (item === 0) item = "A";
          if (item === 1) item = "B";
          if (item === 2) item = "C";
          if (item === 3) item = "D";
          if (item === 4) item = "E";
          if (item === 5) item = "F";
          if (item === 6) item = "G";
          if (item === 7) item = "H";
          return item;
        })
        .join(",");
    },
  },
  methods: {
    // 改变页数
    changeCurrentPage(index) {
      this.$refs.swiper.swipeTo(index);
      this.submit = !this.submit;
    },
    // 收藏
    collect() {
      this.$http
        .get(
          "/api/mzcy/tklb/stscjl?id=" +
            this.practiceList[this.current_page].id +
            "&discern_id=" +
            this.$route.query.id
        )
        .then((res) => {
          Toast({
            duration: 1000,
            message: res.data.msg,
            overlay: true,
            forbidClick: true,
          });
        });
    },
    // 移除收藏
    removeCollect() {
      this.$http
        .get(
          "/api/mzcy/tklb/stscqx?id=" +
            this.practiceList[this.current_page].id +
            "&discern_id=" +
            this.$route.query.id
        )
        .then((res) => {
          Toast({
            duration: 1000,
            message: res.data.msg,
            overlay: true,
            forbidClick: true,
          });
          this.loadData();
        });
    },
    // 移除错题
    removeError() {
      this.$http
        .get(
          "/api/mzcy/tklb/yhctqx?id=" +
            this.practiceList[this.current_page].id +
            "&discern_id=" +
            this.$route.query.id
        )
        .then((res) => {
          Toast({
            message: res.data.msg,
            overlay: true,
            forbidClick: true,
          });
          this.loadData();
        });
    },
    checkChange(value) {
      // console.log(value, "value");
      if (this.practiceList[this.current_page].type !== 2) {
        if (this.answer.answer.length > 0) {
          const answer = [];
          answer.push(value);
          this.answer.answer = answer;
        } else {
          this.answer.answer.push(value);
        }
        let current = [...this.answer.answer].sort().join(",");
        let correct = [...this.practiceList[this.current_page].correctValue]
          .sort()
          .join(",");
        if (current === correct) {
          this.answerMake[this.current_page] = true;
          this.answerMake = [...this.answerMake];
          Toast({
            duration: 1000,
            message: "回答正确",
            overlay: true,
            forbidClick: true,
          });
          if (this.setTimeoutId) {
            clearTimeout(this.setTimeoutId);
            this.setTimeoutId = null;
          }
          this.setTimeoutId = setTimeout(() => {
            this.$refs.swiper.next();
          }, 2100);
        } else {
          this.answerMake[this.current_page] = false;
          this.answerMake = [...this.answerMake];
          if (this.setTimeoutId) {
            clearTimeout(this.setTimeoutId);
            this.setTimeoutId = null;
          }
          this.setTimeoutId = setTimeout(() => {
            this.$refs.swiper.next();
          }, 2100);
        }
        this.answer.status = true;
        this.answerList[this.current_page] = {
          status: true,
          answer: [...this.answer.answer],
        };
      } else {
        let index = this.answer.answer.indexOf(value);
        if (index !== -1)
          this.answer.answer = this.answer.answer
            .slice(0, index)
            .concat(this.answer.answer.slice(index + 1));
        if (index === -1) this.answer.answer.push(value);
      }
    },
    changePage(type) {
      this.$refs.swiper[type]();
    },
    onChange(index) {
      // console.log(index);
      this.current_page = index;
      // console.log(this.answerList);
      this.answer = {
        status: this.answerList[this.current_page].status,
        answer: [...this.answerList[this.current_page].answer],
      };
      // console.log(this.answer);
    },
    confirm() {
      if (this.answer.answer.length <= 0) {
        Toast({
          duration: 1000,
          message: "请选择你的答案再确认",
          overlay: true,
          forbidClick: true,
        });
        return;
      }

      let current = [...this.answer.answer].sort().join(",");
      let correct = [...this.practiceList[this.current_page].correctValue]
        .sort()
        .join(",");
      if (current === correct) {
        this.answerMake[this.current_page] = true;
        this.answerMake = [...this.answerMake];
        Toast({
          duration: 1000,
          message: "回答正确",
          overlay: true,
          forbidClick: true,
        });

        setTimeout(() => {
          this.$refs.swiper.next();
        }, 2100);
      } else {
        this.answerMake[this.current_page] = false;
        this.answerMake = [...this.answerMake];
        if (this.setTimeoutId) {
          clearTimeout(this.setTimeoutId);
          this.setTimeoutId = null;
        }
        this.setTimeoutId = setTimeout(() => {
          this.$refs.swiper.next();
        }, 2100);
      }
      // this.$refs.swiper.next();
      this.answer.status = true;
      this.answerList[this.current_page] = {
        status: true,
        answer: [...this.answer.answer],
      };
      // console.log(this.answerList[this.current_page]);
      // console.log(this.answerList);
    },
    loadData() {
      // 页面的标题
      this.practiceTitle = this.$route.query.title || "标题";
      const baseApi =
        this.$route.query.type == 1
          ? "/api/mzcy/tklb/yhctzs"
          : "/api/mzcy/tklb/stsczs";
      this.$http.get(`${baseApi}?id=${this.$route.query.id}`).then((res) => {
        // console.log(res.data, "res");
        if (res.status === 200) {
          // 当前页数
          this.current_page = parseInt(res.data.current_page)
            ? parseInt(res.data.current_page) - 1
            : 0;
          // 总页数
          this.total_page = res.data.total;
          // 练习习题列表
          let practiceList = [];
          practiceList = res.data.data.datas.map((item) => {
            // // console.log(item);
            // 选项
            let selectOptions = [];
            // 答案
            let correctValue = [];
            for (var key in item.xz) {
              // // console.log(key, "key");
              let val = key.split("value")[1];
              if (val === "a") val = 0;
              if (val === "b") val = 1;
              if (val === "c") val = 2;
              if (val === "d") val = 3;
              if (val === "e") val = 4;
              if (val === "f") val = 5;
              if (val === "g") val = 6;
              if (val === "h") val = 7;
              selectOptions.push({ value: val, text: item.xz[key] });
            }
            // // console.log(selectOptions);
            // 多选
            if (item.type === 2) {
              correctValue = item.value;
            } else {
              // 单选
              correctValue.push(item.value);
            }

            // console.log(item.record, "item");
            this.answerList.push({
              answer: [],
              status: false,
            });
            this.answer = {
              status: this.answerList[this.current_page].status,
              answer: [...this.answerList[this.current_page].answer],
            };
            // // console.log(this.answerList, "111");
            // type  题型
            // title 题目
            // record 用户答案
            // analysis 题目解析
            return {
              id: item.id,
              selectOptions,
              correctValue,
              type: item.type,
              title: item.title,
              analysis: item.analysis,
            };
          });
          // console.log(this.answerMake, 111);
          // // console.log(practiceList);
          this.practiceList = practiceList;
        }
      });
    },
  },
};
</script>

<style>
@import url("../css/practiceTest.css");
/* .operation {
  bottom: 0;
} */
</style>
